/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.scraper.textyard;

import app.scraper.textyard.model.Book;
import app.scraper.textyard.model.Department;

import com.csvreader.CsvWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 * 
 * @author Luis Javier
 */
/* this class export the results in cvs file */
public class ResultsExporter {

	private static final char DELIMITER = ',';
	public String file;// File path

	public ResultsExporter(String file) {
		if (!file.endsWith(".csv")) {
			file = file + ".csv";
		}
		this.file = file;
	}

	public void export(final TreeMap<Department, ArrayList<Book>> resultMap) {
		File exportFile = new File(file);
		try {
			if (!exportFile.exists()) {
				setupFileHeaders(exportFile);
			}
			
			CsvWriter writer = new CsvWriter(new FileWriter(exportFile, true), ',');
			
			for (Department d : resultMap.keySet()) {
				for (Book b : resultMap.get(d)) {
					writer.write(b.getName());
					writer.write(b.getAuthors());
					writer.write(b.getISBN());
					writer.write(b.getEdition());
					writer.write(b.getPublisher());
					writer.write(b.getRequired());
					writer.write(d.getTerm().getSchoolName());
					writer.write(d.getTerm().getTermName());
					writer.write(d.getDepCode());
					writer.write(b.getFullClassName());
					writer.write(b.getBookstorePrice());
					writer.write(b.getLowestPrice());
					writer.endRecord();
				}
			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			Logger.getLogger(ResultsExporter.class.getName()).log(Level.SEVERE, null, e);
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error Exporting Results", JOptionPane.ERROR_MESSAGE);
		}
	}

	private void setupFileHeaders(final File exportFile) throws IOException {
		CsvWriter writer = new CsvWriter(new FileWriter(exportFile, false), DELIMITER);
		writer.write("Title");
		writer.write("Authors");
		writer.write("ISBN");
		writer.write("Edition");
		writer.write("Publisher");
		writer.write("Required");
		writer.write("School");
		writer.write("Term");
		writer.write("Department");
		writer.write("Course");
		writer.write("New, $");
		writer.write("Used, $");
		writer.endRecord();
		writer.flush();
		writer.close();
	}

}
